const express = require("express")
const Router = express.Router
const router = new Router()
const sha1 = require("sha1")

const reply = require("../reply")
const Wechat = require("../wechat/wechat")
const { url } = require("../config")

const wechat = new Wechat()

router.get("/search", async (req, res) => {
    // 首先生成签名
    // 1. 获取到参数
    const { ticket } = await wechat.fetchTicket()
    const timestamp = Date.now(), jsapi_ticket = ticket, noncestr = Math.random().toString().split(".")[1]
    // 2. 进行字典排序
    const str = [
        `jsapi_ticket=${jsapi_ticket}`,
        `timestamp=${timestamp}`,
        `url=${url}/search`,
        `noncestr=${noncestr}`,
    ].sort().join("&")

    console.log("str", str)
    // 3. 进行sha1加密
    const signature = sha1(str)
    // 4. 将相关的参数传入到网页中
    res.render("search", { signature, noncestr, timestamp, appID })
})

router.use(reply())

module.exports = router